package com.cskaoyan.gateway.controller.user;

import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.commons.tool.utils.CookieUtil;
import com.mall.user.IKaptchaService;
import com.mall.user.ILoginService;
import com.mall.user.IRegisterService;
import com.mall.user.annotation.Anoymous;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dto.*;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @Author: DLX
 * @Date: 2021/6/20 15:50
 * @Description:
 **/
@RestController
@RequestMapping("/user")
public class RegisterController {

    @Reference
    private IKaptchaService iKaptchaService;

    @Reference
    private IRegisterService registerService;

    @Reference
    private ILoginService loginService;

    @PostMapping("/register")
    @Anoymous
    public ResponseData register(@RequestBody Map<String, String> map, HttpServletRequest request) {
        String userName = map.get("userName");
        String userPwd = map.get("userPwd");
        String captcha = map.get("captcha");
        String email = map.get("email");

        // 验证码
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        String uuid = CookieUtil.getCookieValue(request, "kaptcha_uuid");
        kaptchaCodeRequest.setUuid(uuid);
        kaptchaCodeRequest.setCode(captcha);
        KaptchaCodeResponse response = iKaptchaService.validateKaptchaCode(kaptchaCodeRequest);
        String code = response.getCode();
        if (!code.equals(SysRetCodeConstants.SUCCESS.getCode())) {
            return new ResponseUtil<>().setErrorMsg(response.getMsg());
        }


        UserRegisterRequest registerRequest = new UserRegisterRequest();
        registerRequest.setEmail(email);
        registerRequest.setUserName(userName);
        registerRequest.setUserPwd(userPwd);
        UserRegisterResponse registerResponse = registerService.register(registerRequest);
        // 成功
        if (registerResponse.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) {
            return new ResponseUtil<>().setData(null);
        }
        // 失败
        return new ResponseUtil<>().setErrorMsg(registerResponse.getMsg());
    }

    /**
     * 注册信息激活
     * @param uid
     * @param username
     * @return
     */
    @GetMapping("verify")
    @Anoymous
    //注册用户激活
    public ResponseData verify(String uid,String username) {
        UserVerifyRequest userVerifyRequest = new UserVerifyRequest(username,uid);
        UserVerifyResponse response =registerService.verify(userVerifyRequest);
        if (!SysRetCodeConstants.SUCCESS.getCode().equals(response.getCode())) {
            return new ResponseUtil<>().setErrorMsg(response.getMsg());
        }
        return new ResponseUtil<>().setData(null);
    }

}